<template>
  <view class="tab-container">
    <my-navbar-top></my-navbar-top>
    <view class="cart-container" v-if="cartList.length != 0 && !isLoad">
      <!-- 列表 -->
      <view class="cart-list">
        <view class="cart-item" v-for="(item, index) in cartList" :key="index">
          <view class="cart-item-left">
            <view class="select" @click.stop="handleSelect(item)">
              <view v-if="item.is_buy == 1" class="select-icon" :class="{
                  active: item.is_select,
                }"></view>
              <view v-else class="select-icon expire-icon"></view>
            </view>
            <view class="cart-item-left-img">
              <view v-if="item.is_buy == 0" class="expire-bg">已失效</view>
              <image :src="item.cover" mode="widthFix" />
            </view>
          </view>
          <view class="cart-item-right">
            <view>
              <view class="name">
                <text>{{ item.name }}</text>
                <view class="x" @click="handleDelete(item.id)">
                  <image src="@/static/images/x.png" mode="widthFix" />
                </view>
              </view>
              <view class="desc" v-if="item.is_buy == 1 && item.brand_name">品牌：{{ item.brand_name }}</view>
              <view class="desc" v-if="item.is_buy == 1 && item.component">面料：{{ item.component }}</view>
              <view class="desc" v-if="item.is_buy == 1 && item.weight">克重：{{ item.weight }}</view>
            </view>
            <view class="opt" v-if="item.is_buy == 1">
              <view class="opt-price">￥{{ item.price }}</view>
              <view class="opt-num">
                <view class="opt-num-minus" @click="changeNum(item, 'sub')">-</view>
                <view class="opt-num-num">
                  <input class="input" :type="item.fixed === 1 ? 'digit' : 'number'"
                    :inputmode="item.fixed === 1 ? 'decimal' : 'numeric'" v-model="item.buy_number"
                    :disabled="item.is_shangxian == 1" @input="
                      (e) => {
                        inputValue(e, item)
                      }
                    " @focus="handleFocus(item)" @blur="handleBlur(item)" />
                </view>
                <view class="opt-num-add" @click="changeNum(item, 'add')">+</view>
              </view>
            </view>
            <view class="opt" v-else>
              <view></view>
              <view class="opt-rebuy">重新选购</view>
            </view>
          </view>
        </view>
      </view>
      <!-- 底部 -->
      <view class="cart-bottom">
        <view class="left" @click="handleSelectAll">
          <!-- 全选  -->
          <view class="all-select" :class="{
              active: is_select_all,
            }">
          </view>
          <view>全选</view>
        </view>
        <view class="right">
          <view class="total-price">￥{{ totalPrice }}</view>
          <view class="settlement" :class="{
              active: totalPrice > 0,
            }" @click="handleSettlement">立即结算</view>
        </view>
      </view>
    </view>
    <view class="cart-container empty-cart" v-if="cartList.length == 0 && !isLoad">
      <image src="/static/images/car.png" mode="widthFix"></image>
      <view>您的购物车为空</view>
    </view>
    <!-- 库存不足 默认弹框 -->
    <stock-popup ref="stockPopup" @close="getCarList"></stock-popup>
    <!-- 限购弹框 需要传入文案 -->
    <stock-popup ref="limitPopup" text1="您已超过今日最大购买限额" text2="请理性消费" @close="limitClose"></stock-popup>

    <custom-tab-bar :current="2"></custom-tab-bar>
  </view>
</template>

<script>
  import stockPopup from '@/components/stockPopup.vue'
  export default {
    name: 'Cart',
    components: {
      stockPopup,
    },
    data() {
      return {
        isLoad: true, // 是否加载中
        // is_buy: 0 失效 1 正常
        cartList: [],
        is_select_all: false,
        totalPrice: 0,
        fixed: 0, // 小数点后几位

        currentItem: {}, // 临时缓存
      }
    },
    onShow() {
      this.isLoad = true
      this.is_select_all = false
      this.totalPrice = 0
      this.currentItem = {}
      this.getCarList()
    },
    methods: {
      // 输入框失焦时，判断库存是否满足
      handleBlur(item) {
        this.currentItem = item // 临时缓存
        this.$api
          .updateCar({
            car_id: item.id,
            buy_number: item.buy_number,
          })
          .then((res) => {
            if (res.code == -1) {
              this.$refs.stockPopup.openPopup()
            }
          })
      },
      handleFocus(item) {
        this.currentItem = item // 临时缓存
        console.log(this.currentItem, '-currentItem')
        this.fixed = item.is_jia_type === 0.1 ? 1 : 0
      },
      // 输入框输入事件
      inputValue(e, item) {
        let value = e.detail.value
        console.log(e.detail, item.fixed)
        let num = this.currentItem.buy_number
        this.$nextTick(() => {
          // 小数点只能出现一次
          if (item.fixed === 1) {
            num = value.replace(/[^\d.]/g, '') // 移除非数字字符
            if (num.split('.').length > 2) {
              num = num.split('.')[0] + '.' + num.split('.')[1]
            }
            // 小数点后只能有1位
            if (num.split('.')[1] && num.split('.')[1].length > 1) {
              num = num.split('.')[0] + '.' + num.split('.')[1].slice(0, 1)
            }
          } else {
            num = value.replace(/[^\d]/g, '') // 移除非数字字符
          }
          this.currentItem.buy_number = num
        })
      },
      // 获取购物车列表
      getCarList() {
        this.$util.showLoading()
        this.isLoad = true
        this.is_select_all = false
        this.totalPrice = 0
        this.currentItem = {}
        this.$api
          .getCarList({})
          .then((res) => {
            if (res.data && res.data.length !== 0) {
              this.cartList = res.data.map((item) => {
                item.is_select = false
                item.fixed = Number(item.is_jia_type) === 0.1 ? 1 : 0
                return item
              })
              this.$store.commit('setCartCount', this.cartList.length)
            } else {
              this.cartList = []
              this.$store.commit('setCartCount', 0)
            }
            uni.hideLoading()
            this.isLoad = false
            console.log(this.isLoad, '-cartList')
          })
          .catch((err) => {
            uni.hideLoading()
            this.isLoad = false
          })
      },
      // 全选
      handleSelectAll() {
        this.cartList.forEach((item) => {
          item.is_select = !this.is_select_all
        })
        this.is_select_all = !this.is_select_all
        this.handleTotal()
      },
      // 选择
      handleSelect(item) {
        item.is_select = !item.is_select
        this.is_select_all = this.cartList.every((item) => item.is_select)
        this.handleTotal()
      },
      // 计算合计
      handleTotal() {
        let total = 0
        this.cartList.forEach((item) => {
          if (item.is_select) {
            total += item.price * item.buy_number
          }
        })
        this.totalPrice = total.toFixed(1)
      },
      // 修改数量
      changeNum(item, type) {
        if (item.is_shangxian == 1) {
          // item.buy_number = item.stock
          return
        }
        let step = Number(item.is_jia_type) || 1,
          fixed = Number(item.is_jia_type) === 0.1 ? 1 : 0
        if (type == 'sub') {
          if (item.buy_number == (fixed === 1 ? 0.1 : 1)) {
            return
          }
          item.buy_number = (Number(item.buy_number) - step).toFixed(fixed)
        }
        if (type == 'add') {
          item.buy_number = (Number(item.buy_number) + step).toFixed(fixed)
        }
        this.handleTotal()
        this.currentItem = item // 临时缓存
        this.$api
          .updateCar({
            car_id: item.id,
            buy_number: item.buy_number,
          })
          .then((res) => {
            if (res.code == -1) {
              this.$refs.stockPopup.openPopup()
            }
          })
      },
      // 立即结算
      handleSettlement() {
        let telephone = uni.getStorageSync('userInfo').telephone || ''
        if (!telephone) {
          uni.navigateTo({
            url: '/pages/user/login/index',
          })
          return
        }
        // 获取已选择的商品
        let selectedList = this.cartList.filter((item) => item.is_select)
        console.log(selectedList, '-已选择的商品')
        let ids = selectedList.map((item) => item.id).join(',')
        let o = {
          car_ids: ids,
        }
        this.$api.orderInfo(o).then((res) => {
          console.log(res)
          if (res.code == 0) {
            uni.navigateTo({
              url: '/pages/settlement/index?ids=' + ids,
            })
          } else if (res.code == -2) {
            this.$refs.limitPopup.openPopup()
          } else {
            this.$refs.stockPopup.openPopup()
          }
        })
      },
      // 限购弹框关闭事件
      limitClose() {
        // 可以干一些事情
      },
      // 删除商品
      handleDelete(id) {
        uni.showModal({
          title: '提示',
          content: '确定删除该商品吗？',
          success: (res) => {
            if (res.confirm) {
              this.$api
                .delCar({
                  car_id: id,
                })
                .then((res) => {
                  if (res.code == 0) {
                    uni.showToast({
                      title: '删除成功',
                    })
                    // 重新获取购物车列表
                    this.getCarList()
                  }
                })
            }
          },
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import './index.scss';
</style>